from flask import Flask,make_response
from flask_restful import reqparse, abort, Api, Resource, request


from wechatpy import parse_message
from wechatpy.replies import TextReply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException


app = Flask(__name__)
api = Api(app)

TOKEN = 'fierytest'

class BaseWx(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('signature', type = str, required = True, help = '参数错误')
    parser.add_argument('timestamp', type = str, required = True, help = '参数错误')
    parser.add_argument('echostr', type = str, required = True, help = '参数错误')
    parser.add_argument('nonce', type = str, required = True, help = '参数错误')


class wx_get(BaseWx):
    def get(self):
        args = self.parser.parse_args()
        print(args.echostr)
        #return api.make_response(args.echostr)
        return make_response(args.echostr)

    def post(self):
        xml_data = request.data
        print(xml_data)
        msg = parse_message(xml_data)
        print(msg.content)


        reply = TextReply(message = msg)
        reply.content = msg.content
        # 转换成 XML
        xml = reply.render()
        return make_response(xml)
#
# try:
#     check_signature(token, signature, timestamp, nonce)
# except InvalidSignatureException:
#     # 处理异常情况或忽略


##
api.add_resource(wx_get, '/wx')



if __name__ == '__main__':
    app.run(debug=True)


#b'<xml><ToUserName><![CDATA[gh_90d02a0868bf]]></ToUserName>\n<FromUserName><![CDATA[oi5FQ5lf6tOAro77sRTLcoH4k3p0]]></FromUserName>\n<CreateTime>1541229096</CreateTime>\n<MsgType><![CDATA[text]]></MsgType>\n<Content><![CDATA[test]]></Content>\n<MsgId>6619528563411705056</MsgId>\n</xml>'
#TextMessage(OrderedDict([('ToUserName', 'gh_90d02a0868bf'), ('FromUserName', 'oi5FQ5lf6tOAro77sRTLcoH4k3p0'), ('CreateTime', '1541229096'), ('MsgType', 'text'), ('Content', 'test'), ('MsgId', '6619528563411705056')]))
